package com.bk.ouat.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bk.ouat.common.JsonResponseMaker;
import com.bk.ouat.dto.UserDto;
import com.bk.ouat.service.UserService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	private final String USER_SESSION_TAG = "userSession";
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private JsonResponseMaker jsonMaker;
	
	
	
	@RequestMapping(value = "user/login.do")
	public String loginView() {
		return "user/login";
	}
	
	@RequestMapping(value = "user/login.ajax", produces="application/json;charset=UTF-8")
	public @ResponseBody String loginAjax(Model model, UserDto parameter, HttpSession session) {
		logger.info("{}", parameter);
		UserDto loginResult = userService.login(parameter);
		String loginResultCode = loginResult.getCode();
		if(loginResultCode.equals("200")){
			session.setAttribute(USER_SESSION_TAG, loginResult);
			return jsonMaker.sucessCode();
		}else if(loginResultCode.equals("404")){
			return jsonMaker.notFoundCode();
		}else{
			return jsonMaker.serviceErrorCode();
		}
	}
	
	@RequestMapping(value = "user/logout.do")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/main.do";
	}
}
